<template>
	<div v-waterMarker class="merak-card merak-container-has-search">
	  <searchBar close-plan close-advanced custom-class="searchHeaderDaily" :placeholder="$t('archive_set_producingCountry.producing_country')"  ref="searchbar" @search-event="searchBarPost">
		  <template #footer>
		    <el-button type="primary" @click="addCountry" v-if="countryAuth?.add?.show">{{$t('archive_set_producingCountry.add_producing_country')}}</el-button>
		  </template>
	  </searchBar>
	  <!-- 表格组件 -->
	  <div class="merak-table-wrapper">
	  	<MerakXTable ref="tableRef" v-bind="tablePayload" :batch-click="handleBatchClick" :handler-click="handleHanderClick"
	  		:query-columns="queryColumns" :query-data="queryData">
			<template #funBtn="{row}">
				<div class="action_btn">
					<el-button class="qf_btn_auto" type="primary" v-if="countryAuth?.edit?.show" link @click="goEdit(row)"> {{$t('merak.edit')}}
					</el-button>
					<el-button class="qf_btn_auto" :disabled="row.used == 0 ? false :true" type="danger" link v-if="countryAuth?.delete?.show" @click="goDelete(row)">{{$t('merak.delete')}} 
					</el-button>
				</div>
			</template>
	  	</MerakXTable>
	  </div>
	  <el-dialog v-model="model" style="width: 500px;" align-center append-to-body>
	    <template #header>
			<div class="editor-title" v-if="countryId != ''">{{$t('archive_set_producingCountry.edit_producing_country')}}</div>
			<div class="editor-title" v-else>{{$t('archive_set_producingCountry.add_producing_country')}}</div>
	    </template>
	    <el-form ref="ruleFormRef" label-position="top" :model="ruleForm" :rules="rules">
			<el-form-item prop="manufacturer_county_ru" :label="$t('archive_set_producingCountry.manufacturer_county_ru')">
				<el-input v-model="ruleForm.manufacturer_county_ru" class="qf_input" />
			</el-form-item>
			<el-form-item prop="manufacturer_county_cn" :label="$t('archive_set_producingCountry.manufacturer_county_cn')">
				<el-input v-model="ruleForm.manufacturer_county_cn" class="qf_input" />
			</el-form-item>
			<el-form-item :label="$t('archive_set_producingCountry.sort')">
				<el-input v-model="ruleForm.sort" v-number class="qf_input" />
			</el-form-item>
	    </el-form>
	    <template #footer>
	      <el-button @click="cancenForm(ruleFormRef)">{{ $t("merak.cancel") }}</el-button>
	      <el-button type="primary" :disabled="disabled" :loading="loading" @click="submitForm(ruleFormRef)">{{ $t("merak.confirm") }}</el-button>
	    </template>
	  </el-dialog>
	</div>
</template>

<script setup lang="tsx" name="producingCountry">
	import type { FormInstance, FormRules, } from "element-plus";
	import {
		reactive,
		computed,
		watch,
		onMounted,
		ref,
		getCurrentInstance
	} from "vue";
	import searchBar from "@/components/SearchBar";
	import MerakXTable, {
		MerakXTableInstance,
		MerakXTableProps
	} from "@/components/MerakXTable";
	
	import {
		getCountryHead,
		getCountryList,
		addCountryItem,
		deleteCountryItem
	} from "@/api/modules/goodsArchive/set/producingCountry";
	import { UserAuthType, getUserAuth } from "@/api/modules/user";
	import { failMsg,successMsg } from "@/utils/messageUtils";
	import { ElMessageBox, ElMessage } from "element-plus";
	const tableRef = ref<MerakXTableInstance>();
	const ruleFormRef = ref<FormInstance>()
	const countryAuth = ref({}) //权限
	const { proxy } = getCurrentInstance()!;
	const model = ref(false)//新增、编辑弹窗
	let ruleForm = reactive({
		"sort": "999",//排序
		"manufacturer_county_ru": "",//国家名称(俄文)
		"manufacturer_county_cn": "",//国家名称(中文)
	})
	const countryId = ref("") //国家id
	//俄语校验
	const russianInput = (rule, value, callback) => {
	  const regexPattern = /[йцукенгшщзхъфывапролджэячсмитьбюё .-]{1,}/; //这里是一个简单的正则表达式，匹配字母和数字
	  if (!value || !regexPattern.test(value)) {
	    return callback(new Error(proxy!.$t("goods_attribute.input_russian_error")));
	  }
	  callback();
	};
	
	const rules = reactive({
		manufacturer_county_ru: [
			{
				required: true,
				message: proxy!.$t("goods_attribute.require"),
				trigger: 'blur',
			},
			// {
			// 	validator: russianInput, 
			// 	trigger: 'blur' ,
			// },
		],
		manufacturer_county_cn: [
			{
				required: true,
				message: proxy!.$t("goods_attribute.require"),
				trigger: 'blur',
			},
		],
	})
	// 页面配置数据
	const state = reactive < {
		thisPageDate: Record < string,string > ;
	} > ({
		thisPageDate: {
			keyword:"",
		},
	
	});
	
	// 动态计算表格的外部筛选数据
	const params = computed(() => ({
		...state.thisPageDate
	}));
	
	// 表格配置属性
	const tablePayload = reactive < MerakXTableProps > ({
		// 列设置存储的数据对照值
		columnsByStore: [],
		// 表格行数据的唯一 key, 跟后端同步
		rowKey: "user_id",
		// 初始化的外部筛选数据
		params,
		// 展示选中列及操作列, 可通过传入对象形式扩展特殊列的渲染插槽, 例如
		// ["selection", { type: 'handle', width: 200, slot: 'custom_slot_name' | ({ row })=> Component }]
		columnType: [{ type: 'handle', width: 100, slot: 'funBtn'}],

	});
	
	// 获取表头数据
	const queryColumns: MerakXTableInstance["queryColumns"] = async () => {
		return getCountryHead().then(({
			code,
			data
		}) => {
			if (code == ResultEnum.SUCCESS) {
				// 克隆表头数据作为列设置的对照数据
				tablePayload.columnsByStore = JSON.parse(JSON.stringify(data.columns));
				return {
					...data,
					columns: [...data.columns].map(column => {
						switch (column.field) {
							case "exception_type_off" :
								// column.slots = {
								// 	default: "employee_one"
								// };
								return column;
							default:
								return column;
						}
					})
				};
			}
		});
	};
	
	/**
	 * 获取表格数据
	 * @param page 分页参数
	 * @param sorts 多重排序参数
	 * @param filters 表头筛选参数
	 * @param from 外部由 tablePayload.params 传入的自定义参数
	 */
	const queryData: MerakXTableInstance["queryData"] = async ({
		page,
		sorts,
		from
	}) => {
		// 创建请求表格数据的参数
		const params: Record < string, any > = {};
		// 如果有分页数据
		if (!!page) {
			Object.assign(params, {
				...page
			});
		}
		// 如果有排序数据
		if (!!sorts) {
			for (let sort of sorts.values()) {
				console.log(sort);
			}
		}
		// 如果有自定义参数
		if (!!from) {
			for (let key of Object.keys(from)) {
				const item = from[key];
				!!item && (params[key] = item);
			}
		}
		// 初始化接口需要传入队列 loading 暴露的 id
		return getCountryList(params).then(({
			code,
			data
		}) => {
			if (code == ResultEnum.SUCCESS) {
				return data.table_data;
			}
		});
	};
	const cancenForm = async (formEl : FormInstance | undefined) => {
		if (!formEl) return
		formEl.resetFields()
		model.value = false
	}
	 
	const submitForm = async (formEl : FormInstance | undefined,isHide:boolean) => {
		
		if (!formEl) return
		await formEl.validate((valid, fields) => {
			//failMsg('所有的属性值(中文)、属性值(俄文)不能为空')
			if (valid) {
				let postData = ruleForm;
				if(countryId.value != ""){
					postData.manufacturer_county_id = countryId.value;
				}
				
				addCountryItem(postData).then(({ code, data,message }) => {
					if (code == 2000) {
						formEl.resetFields();
						ruleForm.sort = "999";
						ruleForm.manufacturer_county_ru = "";
						ruleForm.manufacturer_county_cn = "";
						countryId.value = "";
						tableRef.value?.reloadData();
						model.value = false;
						// successMsg(proxy!.$t("goods_attribute.add_success"));
						// formEl.resetFields();
						// ruleForm.prop_sort_detail = "";
						// ruleForm.prop_sort_filter = "";
						// ruleForm.sort_prop_detail_focal = "";
						// tableConfig.tableData = [];
						// state.refresh = true;
						// if(!isHide){
						// 	emit('close',state.refresh)
						// }
					} else {
						failMsg(message)
					}
				})
			} else {
				console.log('error submit!', fields)
			}
		})
	}
	//触发了快速搜索或者搜索方案
	const searchBarPost = params => {
		//console.log(params)
		let postParams = {
			...params.params,
		};
		state.thisPageDate.keyword = params.search;
	};
	const init = async () => {
		//queryStatData();
		getUserAuth("producingCountry").then(({ code, data }) => {
		    if (code == ResultEnum.SUCCESS) {
				countryAuth.value = data
		    }
		});
	};
	const addCountry = () => {
		model.value = true;
		countryId.value = ""
		ruleForm.sort = "999"
		ruleForm.manufacturer_county_ru = ""
		ruleForm.manufacturer_county_cn = ""
	};
	
	const goEdit = row => {
		model.value = true;
		countryId.value = row.manufacturer_county_id
		ruleForm.sort = row.sort
		ruleForm.manufacturer_county_ru = row.manufacturer_county_ru
		ruleForm.manufacturer_county_cn = row.manufacturer_county_cn
	};
	const goDelete = row => {
		let data = {
			manufacturer_county_id:row.manufacturer_county_id
		}
		ElMessageBox.confirm(proxy!.$t("archive_set_producingCountry.country_warning"), proxy!.$t("merak.tip_modal"), {
		  confirmButtonText: proxy!.$t("merak.confirm"),
		  cancelButtonText: proxy!.$t("merak.cancel"),
		  type: "warning"
		}).then(() => {
		  deleteCountryItem(data).then(({ code, data,message }) => {
		  	if (code == 2000) {
		  		tableRef.value?.reloadData();
		  		successMsg(proxy!.$t("merak.delete_success"));
		  	} else {
		  		failMsg(message)
		  	}
		  })
			
		});
		
	};
	
	onMounted(() => {
		init();
	})
</script>

<style type="text/css" scoped>
	@import "./index.scss";
</style>